package com.jlnk.androidfmc;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jlnk.androidfmc.entity.CartItem;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class PaymentActivity extends AppCompatActivity {
    private List<CartItem> cartItems;
    private TextView textViewTotalAmount;
    private Button buttonProceedToPay;
    private RecyclerView recyclerViewOrderItems;
    private OrderItemsAdapter orderItemsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);

        // 初始化组件
        textViewTotalAmount = findViewById(R.id.textView_total_amount);
        buttonProceedToPay = findViewById(R.id.button_proceed_to_pay);
        recyclerViewOrderItems = findViewById(R.id.recyclerView_order_items);
        orderItemsAdapter = new OrderItemsAdapter(); // 传递当前Activity的引用

        // 设置RecyclerView
        recyclerViewOrderItems.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewOrderItems.setAdapter(orderItemsAdapter);

        // 从Intent获取数据
        Intent intent = getIntent();
        double totalAmount = intent.getDoubleExtra("TOTAL_AMOUNT", 0);
        String selectedItemsJson = intent.getStringExtra("SELECTED_ITEMS_JSON");

        // 设置总金额
        setTotalAmount(totalAmount);

        // 展示选中的商品项
        displaySelectedItems(selectedItemsJson);

        // 设置支付按钮的点击事件
        buttonProceedToPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                proceedToPayment();
            }
        });
    }

    private void setTotalAmount(double amount) {
        String formattedAmount = String.format("¥%.2f", amount);
        textViewTotalAmount.setText(formattedAmount);
    }

    // PaymentActivity 中的 proceedToPayment 方法
    private void proceedToPayment() {
        Intent intent = new Intent(PaymentActivity.this, OrderDetailsActivity.class);

        // 确保传递的数据不为空
        if (cartItems != null && !cartItems.isEmpty()) {
            intent.putExtra("ORDER_ITEMS", serializeCartItems());
        } else {
            Log.e("PaymentActivity", "Cart items list is empty, not passing data.");
        }

        // 确保 totalAmountStr 不为空
        String totalAmountStr = textViewTotalAmount.getText().toString();
        if (!totalAmountStr.isEmpty()) {
            intent.putExtra("TOTAL_AMOUNT", totalAmountStr.replaceAll("[^\\d.]", ""));
        } else {
            Log.e("PaymentActivity", "Total amount string is empty, not passing data.");
        }

        startActivity(intent);
        finish();
    }
    @NonNull
    private String serializeCartItems() {
        Gson gson = new Gson();
        // 使用Gson.toJson处理空列表，避免返回null
        return gson.toJson(cartItems == null ? new ArrayList<>() : cartItems);
    }
    private void displaySelectedItems(String selectedItemsJson) {
        if (selectedItemsJson != null && !selectedItemsJson.isEmpty()) {
            Gson gson = new Gson();
            Type type = new TypeToken<ArrayList<CartItem>>(){}.getType();
            cartItems = gson.fromJson(selectedItemsJson, type); // 确保结果不为 null
            orderItemsAdapter.setItems(cartItems); // 设置适配器的数据
            recyclerViewOrderItems.setAdapter(orderItemsAdapter); // 设置适配器到 RecyclerView
        } else {
            Log.e("PaymentActivity", "Selected items JSON is null or empty");
        }
    }

    public class OrderItemsAdapter extends RecyclerView.Adapter<OrderItemsAdapter.OrderItemViewHolder> {
        private List<CartItem> items;

        public void setItems(List<CartItem> items) {
            this.items = items;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public OrderItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order_detail, parent, false);
            return new OrderItemViewHolder(view);

        }

        @Override
        public void onBindViewHolder(@NonNull final OrderItemViewHolder holder, int position) {
            CartItem item = items.get(position);
            holder.tvGoodName.setText(item.getName());
            holder.tvGoodsPrice.setText(String.format("￥%.2f", item.getPrice()));
            holder.tvGoodsNum.setText(String.valueOf(item.getQuantity()));

            // 计算总金额
            double totalPrice = item.getPrice() * item.getQuantity();
            // 设置总金额的文本
            holder.tvGoodsTotalPrice.setText(String.format("总计: ￥%.2f", totalPrice));

            // 使用 Glide 加载图片
            Glide.with(PaymentActivity.this) // 使用当前 Activity 作为上下文
                    .load(item.getImagePath()) // 加载图片路径
                    .into(holder.ivItemImage); // 将图片设置到对应的 ImageView
        }
        @Override
        public int getItemCount() {
            return items == null ? 0 : items.size();
        }

        public class OrderItemViewHolder extends RecyclerView.ViewHolder {
            public TextView tvGoodName;
            public TextView tvGoodsPrice;
            public TextView tvGoodsNum;
            public TextView tvGoodsTotalPrice;
            public ImageView ivItemImage; // 确保这里声明了 ImageView

            public OrderItemViewHolder(@NonNull View itemView) {
                super(itemView);
                tvGoodName = itemView.findViewById(R.id.tv_good_name);
                tvGoodsPrice = itemView.findViewById(R.id.tv_goods_price);
                tvGoodsNum = itemView.findViewById(R.id.tv_goods_num);
                tvGoodsTotalPrice = itemView.findViewById(R.id.tv_goods_total_price);
                ivItemImage = itemView.findViewById(R.id.iv_goods); // 初始化 ImageView
            }
        }
    }
}